package com.zeoy.keeplivetestdemo.service;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import com.zeoy.keeplivetestdemo.aidl.KeepLiveAidlInterface;
import com.zeoy.keeplivetestdemo.utils.ServiceCheckUtils;

/**
 * Created by Administrator on 2018\3\22 0022.
 */

@SuppressLint("OverrideAbstract")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class NotificationListenerService extends android.service.notification.NotificationListenerService {
    private IBinder binder;
    private ServiceConnection connection;
    private  Intent intent;


    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        startService(intent);
        bindService(intent,connection,BIND_IMPORTANT);
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        startService(intent);
        bindService(intent,connection,BIND_IMPORTANT);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intent1 = new Intent(NotificationListenerService.this,ForeGroundService.class);
        Log.e("zeoy","【广播监听服务重新开启】");
        if (!ServiceCheckUtils.isServiceWorked(this,"com.zeoy.keeplivetestdemo.service.ForeGroundService")){
            Log.e("zeoy", "【通知   -  启动  -  前台】");
            startService(intent1);
        }
        bindService(intent1,connection,BIND_IMPORTANT);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(NotificationListenerService.this,ForeGroundService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("zeoy", "【通知   -  断开连接前台  -  启动前台】");
                startService(intent);
                bindService(intent,connection,BIND_IMPORTANT);
            }
        };

        binder = new KeepLiveAidlInterface.Stub() {
            @Override
            public String getServiceName() throws RemoteException {
                return "NotificationListenerService";
            }
        };
    }
}
